package org.mixare;

import java.util.Collections;

import org.mixare.data.Json;
import org.mixare.gui.Globals;

public class DownloadTimer implements Runnable {
	MixContext ctx;
	MixState state;

	private int retry;
	private boolean stop = false, pause = false;

	public DownloadTimer(MixContext ctx, MixState state) {
		this.ctx = ctx;
		this.state = state;
	}

	public void run() {
		stop = false;
		pause = false;
		while (!stop) {
			while (!stop && !pause) {
				String response;
				try {
					synchronized(ctx) {
						response = Globals.sendPostRequest("req_id=UPDATE&user="+ctx.mixView.id+"&lng="+ctx.curLoc.getLongitude()+"&lat="+ctx.curLoc.getLatitude());
					}
					int code = Integer.parseInt(response.substring(0, response.indexOf(";")));
					String line = response.substring(response.indexOf(";") + 1);
					if(code == 200){
						if(line.startsWith("{")){
							String caughtBy = Globals.getJsonParameter(line, "caught by"); 

							if(!caughtBy.equals("0")){
								state.onBeenCaught(ctx, caughtBy);
							}
							else {
								String exp = Globals.getJsonParameter(line, Globals.EXP);
								if (!exp.equals(ctx.mixView.experience))
									state.onCatch(ctx, line);
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				// Download points
				initDownload();
				while (!ctx.downloadManager.isReqComplete(state.downloadId))
					sleep(50);
				state.dRes = ctx.getDownloader().getReqResult(state.downloadId);
				if (state.dRes.error && retry < 3) {
					retry++;
					state.nextLStatus = MixState.NOT_STARTED;

				} else {
					retry = 0;
					state.nextLStatus = MixState.DONE;
					synchronized (ctx.downloadTimer) {
						if (state.dRes.obj != null) {
							state.jLayer = (Json) state.dRes.obj;

							// Sort markers by cMarker.z
							Collections.sort(state.jLayer.markers, new MarkersOrder());
						}
					}
				}
				ctx.mixView.augScreen.postInvalidate();
				sleep(200);
			}
			while (!stop && pause)
				sleep(100);
		}
	}

	public void initDownload() {
		DownloadRequest request = new DownloadRequest();
		request.url = ctx.getStartUrl();
		state.startUrl = ctx.getStartUrl();
		state.downloadId = ctx.getDownloader().submitJob(request);
	}

	public void stop() {
		stop = true;
	}

	public void pause() {
		pause = true;
	}

	public void restart() {
		pause = false;
	}

	private void sleep(long ms) {
		try {
			Thread.sleep(ms);
		} catch (java.lang.InterruptedException ex) {

		}
	}

	public boolean isPaused() {
		return pause;
	}
}
